<template>
  <div class="thematic-view">
    <!-- 左侧配置面板 -->
    <div class="left-panel">
      <!-- 空白容器，已去除配置项内容 -->
       <Map :layer-manager="layerManager" />
    </div>

    <!-- 中间地图显示区域 -->
    <div class="center-panel">
      <ThematicMapView 
        ref="thematicMapRef"
        :config="currentConfig"
      />
    </div>

    <!-- 右侧AI对话框 -->
    <div class="right-panel">
      <ChatDialog 
        ref="chatDialogRef"
        :is-loading="isLoading"
        @message-sent="handleMessageSent"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import ThematicConfig from '@/components/ThematicConfig.vue';
import ThematicMapView from '@/components/ThematicMapView.vue';
import ChatDialog from '@/components/ChatDialog.vue';
import { runThematicAgent, thematicChatHistory } from '@/agent.js';
import Map from '@/components/Map.vue';
import { useLayerControl } from '@/composables/useLayerControl.js';
import { LayerStateManager } from '@/module/LayerManager.js';

const thematicMapRef = ref(null);
const chatDialogRef = ref(null);
const isLoading = ref(false);

// 全局唯一 LayerStateManager 实例
const layerManager = new LayerStateManager();

// 将图层管理器设置为全局可访问
window.globalLayerManager = layerManager;

// 明确thematicTools对象，直接调用layerManager方法，支持传入config
const thematicTools = {
  loadAllWind: (date, time, config = null) => layerManager.loadAllWind(date, time, config),
  loadAllCurrent: (date, time, config = null) => layerManager.loadAllCurrent(date, time, config),
  loadAllSeatemp: (date, time, config = null) => layerManager.loadAllSeatemp(date, time, config),
  removeWind: (config = null) => layerManager.removeWind(config),
  removeCur: (config = null) => layerManager.removeCur(config),
  removeSeatemp: (config = null) => layerManager.removeSeatemp(config)
};

const layerControl = useLayerControl(layerManager); // 传递同一个layerManager实例

const currentConfig = reactive({
  dataSource: 'cityPopulation',
  thematicType: 'point',
  colorScheme: 'blue',
  showGrid: true,
  showScale: true,
  showLegend: true,
  showLabels: true,
  opacity: 0.8,
  // 风浪流专题图配置
  dateShumo: '2025062609',
  layers: {
    wind: true,
    wave: false,
    current: false
  },
  displayMode: 'single',
  windOptions: {
    showArrow: true,
    showParticle: false,
    showFeather: false
  },
  waveOptions: {
    showArrow: false,
    showParticle: true,
    showLabel: false
  },
  currentOptions: {
    showArrow: true,
    showParticle: true,
    showLand: true
  }
});

// 初始化时添加欢迎消息
onMounted(() => {
  addMessageToChat('您好！我是您的地理专题图制作助手。我可以帮您根据不同的数据源生成各种类型的专题图，包括点符号图、热力图、流向图等。您可以通过左侧面板调整配置，或者直接告诉我您想要制作什么样的专题图！', 'agent');
});

const addMessageToChat = (text, author) => {
  if (chatDialogRef.value) {
    chatDialogRef.value.addMessage({
      id: Date.now() + Math.random(),
      text,
      author, // 'user', 'agent', or 'thought'
      timestamp: new Date(),
    });
  }
};

const handleConfigChange = (newConfig) => {
  Object.assign(currentConfig, newConfig);
};

const handleGenerateMap = (config) => {
  Object.assign(currentConfig, config);
  addMessageToChat(`正在生成${getDataSourceLabel(config.dataSource)}的${getThematicTypeLabel(config.thematicType)}...`, 'agent');
};

const handleMessageSent = async (messageText) => {
  let t1 = new Date().getTime();
  addMessageToChat(messageText, 'user');
  isLoading.value = true;


  const onIntermediateStep = (thought) => {
    addMessageToChat(thought, 'thought');
  };

  try {
    const finalResult = await runThematicAgent(messageText, onIntermediateStep, thematicTools);
    
    // 最多保留3条记录
    if (thematicChatHistory.length >= 3) {
      thematicChatHistory.shift();
    }
    thematicChatHistory.push({ role: "user", content: messageText });
    thematicChatHistory.push({ role: "assistant", content: finalResult });
    
    // 耗时多少秒
    let t2 = new Date().getTime();
    console.log(`耗时：${(t2 - t1) / 1000}秒`);
    addMessageToChat(finalResult, 'agent');
  } catch (error) {
    console.error("Error running thematic agent:", error);
    addMessageToChat(`发生错误: ${error.message}`, 'agent');
  } finally {
    isLoading.value = false;
  }
};

// 辅助函数
const getDataSourceLabel = (dataSource) => {
  const labelMap = {
    cityPopulation: '城市人口',
    provinceGDP: '省份GDP',
    airQuality: '空气质量',
    temperatureData: '温度分布',
    trafficFlow: '交通流量',
    windWaveCurrent: '风浪流专题图'
  };
  return labelMap[dataSource] || '数据';
};

const getThematicTypeLabel = (type) => {
  const labelMap = {
    point: '点符号图',
    choropleth: '分级统计图',
    isoline: '等值线图',
    flow: '流向图',
    heatmap: '热力图',
    '3dbar': '三维柱状图'
  };
  return labelMap[type] || '专题图';
};
</script>

<style scoped>
.thematic-view {
  display: flex;
  width: 100%;
  height: calc(100vh - 60px); /* 减去头部高度 */
  background-color: #f5f7fa;
}

.left-panel {
  width: 320px;
  min-width: 320px;
  height: 100%;
  background: white;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.center-panel {
  flex: 1;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.right-panel {
  width: 400px;
  min-width: 400px;
  height: 100%;
  position: relative;
  background: #f9fafb;
  border-left: 1px solid #e0e0e0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 280px;
    min-width: 280px;
  }
  
  .right-panel {
    width: 350px;
    min-width: 350px;
  }
}

@media (max-width: 768px) {
  .thematic-view {
    flex-direction: column;
    height: calc(100vh - 60px); /* 减去头部高度 */
  }
  
  .left-panel {
    width: 100%;
    min-width: auto;
    height: 200px;
    order: 2;
  }
  
  .center-panel {
    width: 100%;
    height: 400px;
    order: 1;
  }
  
  .right-panel {
    width: 100%;
    min-width: auto;
    height: 300px;
    order: 3;
  }
}

/* 自定义滚动条样式 */
:deep(.thematic-config) {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

:deep(.thematic-config::-webkit-scrollbar) {
  width: 6px;
}

:deep(.thematic-config::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.thematic-config::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.thematic-config::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}
</style> 